package com.类的初始化;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;

public class Student implements Cloneable, Serializable {

	private int id;
	public Student() {

	}
	public Student(Integer id) {
		this.id = id;
	}
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}

	public static void main(String[] args) throws Exception {

		System.out.println("使用new关键字创建对象：");
		Student stu1 = new Student(123);
		System.out.println(stu1);
		System.out.println(" --------------------------- ");

		System.out.println("使用Class类的newInstance方法创建对象：");
		Student stu2 = Student.class.newInstance(); // 对应类必须具有无参构造方法，且只有这一种创建方式
		System.out.println(stu2);
		System.out.println(" --------------------------- ");

		System.out.println("使用Constructor类的newInstance方法创建对象：");
		Constructor<Student> constructor = Student.class.getConstructor(Integer.class); // 调用有参构造方法
		Student stu3 = constructor.newInstance(123);
		System.out.println(stu3);
		System.out.println(" --------------------------- ");

		System.out.println("使用Clone方法创建对象：");
		Student stu4 = (Student) stu3.clone();
		System.out.println(stu4);
		System.out.println(" --------------------------- ");

		System.out.println("使用(反)序列化机制创建对象：");
		// 写对象
		ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("student.bin"));
		output.writeObject(stu4);
		output.close();

		// 读取对象
		ObjectInputStream input = new ObjectInputStream(new FileInputStream("student.bin"));
		Student stu5 = (Student) input.readObject();
		System.out.println(stu5);

	}
}
